const CFG = require('../config');
const rCache = require('../model/redis_cache');
const FUN = require('../comm/func');
const fs = require('fs');
const path = require('path');
const HJSON = require('hjson');
const {promisify} = require('util'); // 将callback转成then
const readFile = promisify(fs.readFile);
const readDir = promisify(fs.readdir);
const writeFile = promisify(fs.writeFile);
const fsStat = promisify(fs.stat);


// 策略缓存初始化
async function PolicyJsonToCache()
{
  await rCache.delNode(rCache.N_Ptype);

  let dirPath = path.resolve('policy_json');
  let allFiles = await readDir(dirPath);

  let i = 0;
  for (fileName of allFiles) {
    let filePath = path.join(dirPath,fileName);
    let typeName = fileName.split('.');
    let stat = await fsStat(filePath);
    if (stat.isFile()) {
      let jsonStr = await readFile(filePath);

      if (typeName[0] == 'all-types') {
        let jsonData = HJSON.parse(jsonStr.toString());
        for (item of jsonData) {
          rCache.set(rCache.N_Ptype, `${typeName[0]}:${item.name}`, item);
        }
      } else {
        let jsonObj = HJSON.parse(jsonStr.toString());
        rCache.setKey(rCache.N_Ptype, typeName[0], HJSON.stringify(jsonObj));
      }
      console.log("cache policy [%d]", i++, typeName[0]);
    }
  }
}

// 传入token，传出user info
async function CheckToken(token)
{
  if (token) {
    let data = await rCache.getAll(rCache.N_UserAuth, token);
    if(data) {
      rCache.expire(rCache.N_UserAuth, token, CFG.USER_TOKEN_EXPIRE); // 每读取一次正确，应该更新下过期时间
      return {token:data.token, uid:data.uid, user:data.user, level:data.level, auth:data.auth};
    }
  }
  return {uid:0};
}

// 计算share tokne得到的uid
function ShareTokenToUid(token)
{
  let arr = token.split('-');
  if (arr.length != 2 || arr[0]*7 != arr[1]) return 0;
  return (arr[0] - 850319) / 7;
}

// 检查用户是否具备某种权限
async function CheckAuth(token, key)
{
  if(token && key){
    let data = await rCache.getAll(rCache.N_UserAuth, token);
    if(data && data.auth){
      let auths = data.auth.split(',');
      return auths.includes(key);
    }
  }
  return false;
}

// qlink策略接口通知
function PolicyUpdateNotify(msg)
{
  const mqttConn = require('../utils/mqttConn');
  let topic;

  //区分调试环境和部署环境，不同环境的发往不同主题
  if (FUN.isLocal()) topic = 'php/policy/local';
  else topic = 'php/policy/api-srv';

  console.log('>>> Policy Notify:', topic, msg);
  mqttConn.singleClientPub(topic, msg);
}

// qlink设备改变通知mq srv
function DevUpdateNotify(msg)
{
  const mqttConn = require('../utils/mqttConn');
  let topic;

  //区分调试环境和部署环境，不同环境的发往不同主题
  if (FUN.isLocal()) topic='srv/notify';
  else topic='srv/notify';

  console.log('>>> Device Notify:', topic, msg);
  mqttConn.singleClientPub(topic, msg);
}

// 处理策略选项中的option用户级别分段
function OptionsLevelHandle(userLevel, options)
{
  let optArray = options.split('|');
  if (optArray.length <= 0) return '';
  if (typeof optArray[userLevel] === 'undefined') return optArray[optArray.length - 1];
  return optArray[userLevel];
}

exports.PolicyJsonToCache = PolicyJsonToCache;
exports.CheckToken = CheckToken;
exports.ShareTokenToUid = ShareTokenToUid;
exports.CheckAuth = CheckAuth;
exports.PolicyUpdateNotify = PolicyUpdateNotify;
exports.DevUpdateNotify = DevUpdateNotify;
exports.OptionsLevelHandle = OptionsLevelHandle;